import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Form,
  // Input,
  Select,
  Icon,
  Button,
  DatePicker,
  Badge,
  Divider,
  BackTop,
} from 'antd';
import StandardTableCustom from '../../customComponents/StandardTableCustom';
import PageHeaderWrapperCustom from '../../customComponents/PageHeaderWrapperCustom';
import Ellipsis from '../../components/Ellipsis';
import SendOutModal from './SendOutModal';
import { isDatetime } from '../../utils/tools';

import styles from './ListOnLine.less';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const status = [
  {
    key: -10000,
    badge: 'error',
    text: '不限',
    value: -10000,
  },
  {
    key: 2,
    badge: 'error',
    text: '未发货',
    value: 2,
  },
  {
    key: 4,
    badge: 'success',
    text: '已发货',
    value: 4,
  },
  {
    key: 5,
    badge: 'success',
    text: '已收货',
    value: 5,
  },
];

let currentQueryParam = null;

@connect(({ productOrder, loading }) => ({
  productOrder,
  loading: loading.models.productOrder,
}))
@Form.create()
class Standard extends PureComponent {
  isMountedFlag = false;

  state = {
    formValues: {},
    orderCreateDataStart: '',
    orderCreateDataEnd: '',
    sendOutData: null,
    sendOutModalVisible: false,
    customData: {
      count: 0,
      list: [],
      pagination: {},
    },
    pageNo: 1,
    pageSize: 10,
  };

  componentDidMount() {
    this.isMountedFlag = true;
    const { pageNo, pageSize } = this.state;
    this.loadData({ pageNo, pageSize });
  }

  componentWillUnmount() {
    this.isMountedFlag = false;
  }

  loadData = (obj, callback) => {
    const { dispatch } = this.props;
    const { orderCreateDataStart, orderCreateDataEnd } = this.state;

    const p = obj || {};

    if (isDatetime(orderCreateDataStart)) {
      p.createstarttime = `${orderCreateDataStart} 00:00:01`;
    }

    if (isDatetime(orderCreateDataEnd)) {
      p.createendtime = `${orderCreateDataEnd} 23:59:59`;
    }

    // 移除临时使用的键值对
    delete p.dateRange;

    dispatch({
      type: 'productOrder/list',
      payload: p,
    }).then(() => {
      const {
        productOrder: { data },
      } = this.props;
      this.setState({ customData: data });

      if (typeof callback === 'function') {
        callback();
      }
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    currentQueryParam = params;

    this.loadData(params);
  };

  handleFormReset = () => {
    const { form } = this.props;
    const { pageSize } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
      orderCreateDataStart: null,
      orderCreateDataEnd: null,
    });

    this.loadData({
      pageNo: 1,
      pageSize,
    });
  };

  refreshGrid = callback => {
    this.loadData(currentQueryParam, callback);
  };

  onOrderCreateDataChange = (date, dateString) => {
    if (dateString.length === 2) {
      this.setState({
        orderCreateDataStart: dateString[0],
        orderCreateDataEnd: dateString[1],
      });
    }
  };

  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      this.loadData({
        ...values,
        pageNo: 1,
        pageSize,
      });
    });
  };

  handleDetailClick = record => {
    const { dispatch } = this.props;
    const { productOrderId } = record;
    const location = {
      pathname: `/productOrder/online/detail/${productOrderId}`,
    };
    dispatch(routerRedux.push(location));
  };

  handleSendOutClick = record => {
    this.setState({
      sendOutData: record,
      sendOutModalVisible: true,
    });
  };

  afterSendOutItemModalOk = (data, callback) => {
    this.setState({
      sendOutModalVisible: false,
    });

    this.refreshGrid(callback);
  };

  afterSendOutItemModalCancel = () => {
    this.setState({
      sendOutModalVisible: false,
    });
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { orderCreateDataStart, orderCreateDataEnd } = this.state;
    const { getFieldDecorator } = form;
    const statusOption = [];
    status.forEach(item => {
      const { text, value } = item;
      statusOption.push(
        <Select.Option key={value} value={value}>
          {text}
        </Select.Option>
      );
    });
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          {/* <Col md={4} sm={24}>
            <FormItem label="关键词">
              {getFieldDecorator('keywords')(<Input placeholder="请输入需要搜索的内容" />)}
            </FormItem>
          </Col> */}
          <Col md={4} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status', {
                rules: [{ required: false, message: '请选择状态!' }],
                initialValue: status[0].value,
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {statusOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="下单时段">
              {getFieldDecorator('dateRange', {
                rules: [{ required: false }],
                initialValue:
                  isDatetime(orderCreateDataStart) && isDatetime(orderCreateDataEnd)
                    ? [moment(new Date(orderCreateDataStart)), moment(new Date(orderCreateDataEnd))]
                    : [],
              })(
                <RangePicker
                  onChange={(date, dateString) => {
                    this.onOrderCreateDataChange(date, dateString);
                  }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { dispatch, loading } = this.props;
    const { customData, sendOutData, sendOutModalVisible } = this.state;
    const columns = [
      {
        title: '订单编号',
        dataIndex: 'orderNo',
        width: 140,
        align: 'center',
      },
      {
        title: '商品主图',
        dataIndex: 'bigImage',
        width: 100,
        align: 'center',
        render: (val, record) => (
          <Fragment>
            <img className={styles.img} src={val} alt={record.productName} />
          </Fragment>
        ),
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '数量',
        dataIndex: 'count',
        width: 80,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '金额',
        dataIndex: 'amount',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              ￥{val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '收货人',
        dataIndex: 'addressContact',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '收货人电话',
        dataIndex: 'addressPhone',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '下单时间',
        dataIndex: 'createTime',
        width: 120,
        align: 'center',
        sorter: false,
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {moment(new Date(val.replace('/', '-'))).format('YYYY-MM-DD')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 120,
        align: 'center',
        filters: status,
        filterMultiple: false,
        onFilter: (value, record) => `${record.status}` === `${value}`,
        render(val, record) {
          let badgeValue = 'default';
          status.forEach(item => {
            const { badge, value } = item;
            if (value === val) {
              badgeValue = badge;
            }
          });
          return <Badge status={badgeValue} text={record.statusNote} />;
        },
      },
      {
        title: '操作',
        width: 156,
        align: 'center',
        // fixed: 'right',
        render: (text, record) => (
          <Fragment>
            <a
              disabled={`${record.status}` !== '2'}
              onClick={() => this.handleSendOutClick(record)}
              className={styles.actionButton}
            >
              <Icon type="export" className={styles.editButton} />
              发货
            </a>
            <a className={styles.actionButton} onClick={() => this.handleDetailClick(record)}>
              <Icon type="project" className={styles.editButton} />
              详情
            </a>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderWrapperCustom title="商品列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTableCustom
              loading={loading}
              data={customData}
              columns={columns}
              expandedRowRender={record => (
                <div>
                  <p>
                    <span className="bold">订单描述：</span>
                    <span>{record.description}</span>
                  </p>
                  <Divider />
                  <p>
                    <span className="bold">
                      收货人：
                      {record.addressContact}
                    </span>
                    <span className="bold" style={{ marginLeft: '20px' }}>
                      收货联系方式：
                      {record.addressPhone}
                    </span>
                    <span className="bold" style={{ marginLeft: '20px' }}>
                      收货地址：
                      {record.fullAddress}
                    </span>
                  </p>
                  {record.status >= 4 ? (
                    <p>
                      <span className="bold">
                        物流方式：
                        {record.logisticsCom}
                      </span>
                      <span className="bold" style={{ marginLeft: '20px' }}>
                        单号：
                        {record.logisticsNu}
                      </span>
                    </p>
                  ) : null}
                </div>
              )}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <SendOutModal
          data={sendOutData}
          visible={sendOutModalVisible}
          dispatch={dispatch}
          afterOK={this.afterSendOutItemModalOk}
          afterCancel={this.afterSendOutItemModalCancel}
        />
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default Standard;
